layui.use(['table', 'admin', 'ax','dropdown','layer'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var layer = layui.layer;
    /**
     * 管理
     */
    var LxSpWzh = {
        tableId: "lxSpWzhTable"
    };

    /**
     * 初始化表格的列
     */
    LxSpWzh.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'spId', hide: true, title: 'id'},
            {field: 'spTxm', sort: true, title: '条形码'},
            {field: 'spGuige', sort: true, title: '规格'},
            {field: 'spName', sort: true, title: '名称'},
            {field: 'spDanwei', sort: true, title: '单位'},
            {field: 'spChandi', sort: true, title: '产地'},
            {field: 'spChuo', sort: true, title: '存货量'},
            {field: 'spSuoshu', sort: true, title: '所属类别'},
            {field: 'spLings', sort: true, title: '零售价'},
            {field: 'spPifa', sort: true, title: '批发价'},
            {field: 'spBz', sort: true, title: '备注'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    aa();
 function aa() {
     $.ajax({
         url: Feng.ctxPath + "/lxSpWzh/list2",
         dataType: 'json',
         type: 'get',
         success: function (data) {
             console.log(data); //使用循环遍历，给下拉列表赋值
             //使用循环遍历，给下拉列表赋值
             $.each(data.data, function (index, value) {
                 $('#dp').append(new Option(value.lbName, value.lbid));// 下拉菜单里添加元素
             });
             layui.form.render("select");
         }
     })
 }


    form.on('select(xmFilter)', function(data){
        var lb = data.value //得到被选中的值
        $("#condition").val(lb);
        LxSpWzh.search();
    });
    /**
     * 点击查询按钮
     */

    LxSpWzh.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        table.reload(LxSpWzh.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
                 aa();
                 // 搜索按钮点击事件
                 $('#btnSearch').click(function () {
                     LxSpWzh.search();
                 });
                 // 添加按钮点击事件
                 $('#btnAdd').click(function () {
                     LxSpWzh.openAddDlg();
                 });
                 // 导出excel
                 $('#btnExp').click(function () {
                     LxSpWzh.exportExcel();
                 });
                 // 购买按钮点击事件
                 $('#xlk').click(function () {
                     LxSpWzh.lb();
                 });
                 $('#goum').click(function (){
                     LxSpWzh.goumai();
                 })
            }
        });
    };



    LxSpWzh.goumai = function (data) {
        let checkRows = table.checkStatus(LxSpWzh.tableId);
        console.log(checkRows.data.length)
        if (checkRows.data.length >= 0) {
            var html = '';
            if (checkRows.data.length <= 6) {
                for (var i = 0; i < checkRows.data.length; i++) {
                    var ch = checkRows.data[i].spChuo
                    var mc = checkRows.data[i].spName
                    var dj = checkRows.data[i].spLings
                    html += '<div>'  + "商品名称 ："+ mc +'<span> | </span>'  + "剩余存货量 ："+  ch + '<span> | </span>'  + "单价 ："+  dj +' <input type="text" placeholder="请输入要购买的数量" id="inputValue' + i + '" class="layui-input">' +
                        '</div>';
                }
            } else {
                Feng.error("单次购买最多只能选择5种商品");
            }

            // 弹窗配置项
            var options = {
                title: '购买商品',
                content: html,
                area: ['500px', '300px'], //
                btn: ['确定', '取消'], // 自定义按钮名称
                yes: function(index, layero) {
                    // 触发确定按钮的回调函数
                    var values = [];
                    for (var i = 0; i < checkRows.data.length; i++) {
                        var inputId = 'inputValue' + i;
                        var inputValue = document.getElementById(inputId).value;
                        values.push(inputValue); //输入值的数组
                    }

                    var min = 10;
                    var max = 20;
                    var randomInt = Math.floor(Math.random() * (max - min + 1)) + min;

                    const currentDate = new Date();
                    const year = String(currentDate.getFullYear()).padStart(4, '0');
                    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                    const day = String(currentDate.getDate()).padStart(2, '0');
                    const hours = String(currentDate.getHours()).padStart(2, '0');
                    const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                    const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                    const dateTimeString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                    var dp = 1;
                    for (var h = 0; h < values.length; h++){
                        var num =Number(values[h]);
                        console.log(values[h],checkRows.data[h].spChuo - values[h] ,Number.isInteger(num))
                        if (values[h] >= 0 && checkRows.data[h].spChuo - values[h] >= 0 && Number.isInteger(num)){
                            dp = 1;
                        }else {
                            dp = -1;
                            break;
                        }
                    };
                    console.log(dp)
                    for (var j = 0; j < values.length; j++) {
                        console.log(dp)
                        if (dp === 1) {
                            var requestData = {
                                ddDdbh: (checkRows.data[j].spTxm) + 'x' + randomInt,
                                ddTxm: checkRows.data[j].spTxm,
                                ddTime: dateTimeString,
                                ddSl: values[j],
                                ddZj: checkRows.data[j].spLings,
                                ddUser: "test"
                            }

                            $.ajax({
                                type: "POST",
                                url: Feng.ctxPath + "/lxDdWzh/add2",
                                data: JSON.stringify(requestData),
                                contentType: "application/json;charset=utf-8",
                                success: function (data) {
                                    Feng.success("购买成功！");
                                    window.location.href = Feng.ctxPath + '/lxSpWzh';
                                },
                                error: function (data) {
                                    Feng.error("购买失败！" + data.responseJSON.message);
                                }

                            });
                        } else {
                            Feng.error("数量输入错误")
                        }

                    }

                    layer.close(index);
                },
                btn2: function(index, layero) {
                    // 触发取消按钮的回调函数

                }
            };
            // 打开弹窗
            layer.open(options);
        }else {
            Feng.error("请选择至少一种商品");
        }
    };

    /**
     * 弹出添加对话框
     */
    LxSpWzh.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/lxSpWzh/add';
    };


    /**
     * 导出excel按钮
     */
    LxSpWzh.exportExcel = function () {
        var checkRows = table.checkStatus(LxSpWzh.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    LxSpWzh.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/lxSpWzh/edit?spId=' + data.spId;
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    LxSpWzh.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/lxSpWzh/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(LxSpWzh.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("spId", data.spId);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + LxSpWzh.tableId,
        url: Feng.ctxPath + '/lxSpWzh/list',
        page: true,
        limit: 20,
        height: "full-60",
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        cols: LxSpWzh.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        LxSpWzh.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        LxSpWzh.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        LxSpWzh.exportExcel();

    });
    // 购买按钮点击事件

    $('#xlk').click(function () {
        LxSpWzh.lb();
        //重新渲染 固定写法
    });
    $('#goum').click(function (){
        LxSpWzh.goumai();
    })

    // 工具条点击事件
    table.on('tool(' + LxSpWzh.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            LxSpWzh.openEditDlg(data);
        } else if (layEvent === 'delete') {
            LxSpWzh.onDeleteItem(data);
        }
    });
});
